<?php
/**
* @file index.php
* Copyright (c) Friends Group. All rights reserved.
* $Id$
*
*/

require_once(realpath(dirname(__FILE__)) . '/config.php');
require_once(realpath(dirname(__FILE__)) . '/includes/common/ServiceFactory.php');

Session::start(0);

$commonService = ServiceFactory::get();
$config = ServiceFactory::get("SystemConfiguration");
$userService = ServiceFactory::get("UserService");
$authService = ServiceFactory::get("AuthenticationService");
$themeDir = "themes/" . $config -> getSetting("theme");

$action = $_REQUEST['action'];
$redirect = $_REQUEST['back'];

if(empty($redirect))
    $redirect = "./index.php";

if ( empty($action) ) 
{
    if (isset($_POST['login']) && !empty($_POST['login']))
        $action = 'login';
}

$logged = $authService -> isAuthenticated();

if(!$logged)
{
    switch($action)
    {
        case 'login':
            $name = $_REQUEST['userLoginName'];
            $pass = $_REQUEST['userLoginPass'];
            
            if(empty($name))
                RedirectMessage::info("Bạn chưa nhập Tên", "Error");
            elseif(empty($pass))
                RedirectMessage::info("Bạn chưa nhập Mật khẩu", "Error");
            else
            {
                try
                {
                    $user = $userService -> findUserByName($name);
                    if($user -> getActivationKey() != null)
                    {
                        RedirectMessage::info("Tài khoản '$name' cần được kích hoạt trước khi sử dụng", "Error");
                        Response::redirect($_SERVER['REQUEST_URI']);
                    }
                    
                    if($user -> getPassword() != sha1($pass))
                    {
                        RedirectMessage::info("Mật khẩu không đúng", "Error");
                        Response::redirect($_SERVER['REQUEST_URI']);
                    }
                    
                    $authService -> login($user);
                    Response::redirect($redirect);
                }
                catch(Exception $ex)
                {
                    RedirectMessage::info($ex -> getMessage(), "Error");
                }
            }
            
            Response::redirect($_SERVER['REQUEST_URI']);
    }
    
    include($themeDir . "/header.php");
}
elseif($logged)
{
    include($themeDir . "/header.php");
    $user = $authService -> getCurrentUser();
    $userService -> updateLastAccessTime($user -> getID());
    $userService -> setUserStatus($user -> getID(), $commonService -> getStatusByName($userService -> getUserOption($user -> getID(), "last-status")), $userService -> getUserOption($user -> getID(), "last-status"));
?>
<div class="Content"></div>
<script type="text/javascript">
    
        var buddyList;
        
        function updateBuddyList(buddyList)
        {
            new Request.JSON
            ({
                url: "<?php echo $config -> getSetting("site-url")."/chat/chat.php "; ?>", 
                secure: false,
                onComplete: function(json)
                {
                    if(json.success == 'true')
                    {
                        buddyList.buildBuddyList(json.items);
                    }
                    else
                        handleError(json);
                    setTimeout('updateBuddyList(buddyList)', 8000);
                }
            }).post({action: 'getBuddyList', userId: '<?php echo $user -> getID() ?>'});
        }
        
        function getBuddyMessage(buddyList)
        {
            new Request.JSON
            ({
                url: "<?php echo $config -> getSetting("site-url")."/chat/chat.php "; ?>", 
                secure: false,
                onComplete: function(json)
                {
                    if(json.success == 'true')
                    {
                        buddyList.newMessage(json.items.messages);
                    }
                    else
                        handleError(json);
                    setTimeout('getBuddyMessage(buddyList)', 1200);
                }
            }).post({action: 'getAllMessages', userId: '<?php echo $user -> getID() ?>'});
        }
        
        function handleError(json)
        {
            if(json.errorCode == '401')
                window.location.href = './logout.php';
            else
                alert(json.message);
        }
        
        jQuery(document).ready(function()
        {
        
            var url = "<?php echo $config -> getSetting("site-url")."/chat/chat.php "; ?>";
            
            var buddyMenu = new ContextMenu
            ({
                id: 'buddyMenu', imgsrc: '<?php echo $themeDir . "/images/"; ?>',
                items: [{name: 'Thêm bạn', imgsrc: 'add.png', id:'addBuddy'}, {name: 'Xem thông tin', imgsrc: 'info.png', id:'getBuddyInfo'}, {name: 'Gửi tin nhắn', imgsrc: 'chat.png', id:'sendBuddyMessage'}, 
                    <?php 
                        if(!$authService -> isUser($user))
                        {
                            echo "{name: 'Gửi thông báo', imgsrc: 'icon-alert.png', id:'sendWarningMessage'},";
                            echo "{name: 'Gửi cảnh cáo', imgsrc: 'icon-error.png', id:'sendAlertMessage'},";
                        }
                      ?>
                    {name: 'Đổi tên', imgsrc: 'edit.png', id:'changeBuddyAlias'}, {name: 'Xóa', imgsrc: 'delete.png', id:'deleteBuddy'}],
                onMenuItem: function(o, e)
                {
                    switch (e) 
                    {
                        case 'addBuddy':
                            newBuddyDlg(buddyList);
                            break;
                        case 'getBuddyInfo':
                            
                            break;
                        case 'changeBuddyAlias':
                            var htmml = '<div class="DlgChangeBuddyAliasContent flora Toolbox" title="Đổi tên buddy">'+
                                            '<p style="margin-bottom: 35px;"><img alt="img" style="float:left;margin-right: 10px;" src="<?php echo $themeDir . "/images"; ?>/question.png"/><span>Nhập tên mới cho buddy</span></p>'+
                                            '<p><label for="newBuddyAlias">Tên buddy:</label><input style="width:158px" type="text" id="newBuddyAlias" /></p>'+
                                        '</div>';
                                
                            j$(htmml).dialog
                            ({
                                id: 'dlgChangeBuddyAlias',
                                resizable: false, width: 270, height: 170,
                                buttons: 
                                {
                                    'Đổi tên buddy': function()
                                    {
                                        var newAlias = j$('div.DlgChangeBuddyAliasContent').find('input#newBuddyAlias').val();
                                        if(newAlias != '')
                                        {
                                            new Request.JSON
                                            ({
                                                url: url, 
                                                secure: false,
                                                onComplete: function(json)
                                                {
                                                    if(json.success == 'true')
                                                        buddyList.buildBuddyList(json.items);
                                                    else
                                                        handleError(json);
                                                }
                                            }).post({action: 'changeBuddyAlias', userId: '<?php echo $user -> getID() ?>', alias: newAlias, buddyName: o});
                                        }
                                        j$(this).dialog('close');
                                    }
                                },
                                close: function(ev, ui)
                                {
                                    ui.remove();
                                },
                                open: function()
                                {
                                    var inputField = j$('div.DlgChangeBuddyAliasContent').find('input#newBuddyAlias');
                                    inputField.focus();
                                    inputField.val(o);
                                }
                            });
                            break;
                        case 'sendBuddyMessage':
                            buddyList.setMessageType('Normal');
                            buddyList.openDlgChat(o);
                            break;
                        <?php 
                            if(!$authService -> isUser($user))
                            {
                          ?>
                        case 'sendWarningMessage':
                            buddyList.setMessageType('Warning');
                            buddyList.openDlgChat(o);
                            break;
                        case 'sendAlertMessage':
                            buddyList.setMessageType('Alert');
                            buddyList.openDlgChat(o);
                            break;
                        <?php
                            }
                          ?>
                        case 'deleteBuddy':
                            var htmml = '<div class="DlgDeleteBuddyContent flora Toolbox" title="Xác nhận xóa buddy">'+
                                            '<p style="margin-top: 35px;"><img alt="img" style="float:left;margin-right: 10px;" '+
                                            'src="<?php echo $themeDir . "/images"; ?>/question.png"/><span>Bạn có chắc là sẽ xóa buddy '+
                                            '<span style="background-color:#eeee00;padding:2px;font-weight:bold;color:#ff0000">'+o+'</span> khỏi danh sách friend của bạn không?</span></p>'+
                                        '</div>';
                            
                            j$(htmml).dialog
                            ({
                                id: 'dlgDeleteBuddy',
                                resizable: false, width: 270, height: 170,
                                buttons: 
                                {
                                    'Xóa buddy': function()
                                    {
                                        new Request.JSON
                                        ({
                                            url: url, 
                                            secure: false,
                                            onComplete: function(json)
                                            {
                                                if(json.success == 'true')
                                                    buddyList.buildBuddyList(json.items);
                                                else
                                                    handleError(json);
                                            }
                                        }).post({action: 'deleteBuddy', userId: '<?php echo $user -> getID() ?>', buddyName: o});
                                        j$(this).dialog('close');
                                    },
                                    'Thôi': function()
                                    {
                                        j$(this).dialog('close');
                                    }
                                },
                                close: function(ev, ui)
                                {
                                    ui.remove();
                                }
                            });
                            break;
                        default:
                            break;
                    }
                }
            });
            
            var groupMenu = new ContextMenu
            ({
                id: 'groupMenu', imgsrc: '<?php echo $themeDir . "/images/"; ?>',
                items: [{name: 'Thêm nhóm', imgsrc: 'add.png', id:'newGroup'},
                    {name: 'Đổi tên nhóm', imgsrc: 'edit.png', id:'renameGroup'}, {name: 'Xóa nhóm', imgsrc: 'delete.png', id:'deleteGroup'}],
                onMenuItem: function(o, e)
                {
                    switch (e) {
                        case 'newGroup':
                            var htmml = '<div class="DlgNewGroupContent flora Toolbox" title="Thêm nhóm">'+
                                            '<p style="margin-bottom: 35px;"><img alt="img" style="float:left;margin-right: 10px;" src="<?php echo $themeDir . "/images"; ?>/question.png"/><span>Nhập tên nhóm muốn thêm</span></p>'+
                                            '<p><label for="newGroupname">Tên nhóm:</label><input style="width:158px" type="text" id="newGroupname" /></p>'+
                                        '</div>';
                        
                            j$(htmml).dialog
                            ({
                                    id: 'dlgNewGroup',
                                    resizable: false, width: 270, height: 170,
                                    buttons: 
                                    {
                                        'Thêm nhóm mới': function()
                                        {
                                            var newName = j$('div.DlgNewGroupContent').find('input#newGroupname').val();
                                            if(newName != '')
                                            {
                                                new Request.JSON
                                                ({
                                                    url: url, 
                                                    secure: false,
                                                    onComplete: function(json)
                                                    {
                                                        if(json.success == 'true')
                                                            buddyList.buildBuddyList(json.items);
                                                        else
                                                            handleError(json);
                                                    }
                                                }).post({action: 'addGroup', userId: '<?php echo $user -> getID() ?>', groupName: newName});
                                            }
                                            j$(this).dialog('close');
                                        }
                                    },
                                    close: function(ev, ui)
                                    {
                                        ui.remove();
                                    },
                                    open: function()
                                    {
                                        j$('div.DlgNewGroupContent').find('input#newGroupname').focus();
                                    }
                            });
                            break;
                        case 'renameGroup':
                            var htmml = '<div class="DlgRenameGroupContent flora Toolbox" title="Đổi tên nhóm">'+
                                            '<p style="margin-bottom: 35px;"><img alt="img" style="float:left;margin-right: 10px;" src="<?php echo $themeDir . "/images"; ?>/question.png"/><span>Nhập tên nhóm mới muốn đổi</span></p>'+
                                            '<p><label for="newGroupname">Tên nhóm:</label><input style="width:158px" type="text" id="newGroupname" /></p>'+
                                        '</div>';
                        
                            j$(htmml).dialog
                            ({
                                    id: 'dlgRenameGroup',
                                    resizable: false, width: 270, height: 170,
                                    buttons: 
                                    {
                                        'Đổi tên nhóm': function()
                                        {
                                            var newName = j$('div.DlgRenameGroupContent').find('input#newGroupname').val();
                                            if(newName != '')
                                            {
                                                new Request.JSON
                                                ({
                                                    url: url, 
                                                    secure: false,
                                                    onComplete: function(json)
                                                    {
                                                        if(json.success == 'true')
                                                            buddyList.buildBuddyList(json.items);
                                                        else
                                                            handleError(json);
                                                    }
                                                }).post({action: renameGroup, userId: '<?php echo $user -> getID() ?>', groupId: o, groupName: newName});
                                            }
                                            j$(this).dialog('close');
                                        }
                                    },
                                    close: function(ev, ui)
                                    {
                                        ui.remove();
                                    },
                                    open: function()
                                    {
                                        j$('div.DlgRenameGroupContent').find('input#newGroupname').focus();
                                    }
                            });
                            break;
                        case 'deleteGroup':
                            var htmml = '<div class="DlgDeleteGroupContent flora Toolbox" title="Xác nhận xóa nhóm">'+
                                            '<p style="margin-top: 35px;"><img alt="img" style="float:left;margin-right: 10px;" '+
                                            'src="<?php echo $themeDir . "/images"; ?>/question.png"/><span>Bạn có chắc là sẽ xóa nhóm '+
                                            '<span style="background-color:#eeee00;padding:2px;font-weight:bold;color:#ff0000">'+j$('#group-'+o).find('span.label').text()+'</span> không? Tất cả các friend trong nhóm sẽ bị xóa theo.</span></p>'+
                                        '</div>';
                                
                            j$(htmml).dialog
                            ({
                                id: 'dlgDeleteGroup',
                                resizable: false, width: 270, height: 170,
                                buttons: 
                                {
                                    'Xóa nhóm': function()
                                    {
                                        new Request.JSON
                                        ({
                                            url: url, 
                                            secure: false,
                                            onComplete: function(json)
                                            {
                                                if(json.success == 'true')
                                                    buddyList.buildBuddyList(json.items);
                                                else
                                                    handleError(json);
                                            }
                                        }).post({action: 'deleteGroup', userId: '<?php echo $user -> getID() ?>', groupId: o});
                                        j$(this).dialog('close');
                                    },
                                    'Thôi': function()
                                    {
                                        j$(this).dialog('close');
                                    }
                                },
                                close: function(ev, ui)
                                {
                                    ui.remove();
                                }
                            });
                            break;
                        default:
                            break;
                    }
                }
            })
            
            buddyList = new BuddyDlgList
            ({
                id: 'buddyList', buddyContextMenu: buddyMenu, 
                groupContextMenu: groupMenu,
                imgsrc: '<?php echo $themeDir . "/images/"; ?>',
                owner: <?php $fullname = $user -> getFirstname() . " " . $user -> getLastname(); echo "{id: 'buddy-{$user -> getNickname()}', name: '$fullname', alias: '$fullname',  avatar: '{$commonService -> getAvatarSrc($user -> getAvatarID(), 2)}', status: '{$userService -> getUserStatus($user -> getID()) -> getStatusText()}'}" ?>,
                onCreate: function(o)
                {
                    new Request.JSON
                    ({
                        url: "<?php echo $config -> getSetting("site-url")."/chat/chat.php "; ?>", 
                        secure: false,
                        onComplete: function(json)
                        {
                            if(json.success == 'true')
                            {
                                buddyList.buildBuddyList(json.items);
                                setTimeout('updateBuddyList(buddyList)', 8000);
                                setTimeout('getBuddyMessage(buddyList)', 2500);
                            }
                            else
                                handleError(json);
                        }
                    }).post({action: 'getBuddyList', userId: '<?php echo $user -> getID() ?>'});
                },
                onStatusChanged: function(newStatus)
                {
                    new Request.JSON
                    ({
                        url: "<?php echo $config -> getSetting("site-url")."/chat/chat.php "; ?>", 
                        secure: false,
                        onComplete: function(json)
                        {
                            if(json.success == 'true')
                                buddyList.buildBuddyList(json.items);
                            else
                                handleError(json);
                        }
                    }).post({action: 'updateMyStatus', userId: '<?php echo $user -> getID() ?>', status: newStatus});
                },
                onToolbarItem: function(id)
                {
                    if(id == 'buttonAddBuddy')
                    {
                        newBuddyDlg(this);
                    }
                    else if(id == 'buttonSendBuddyMessage')
                    {
                        var htmml = '<div class="DlgSendBuddyMessageContent flora Toolbox" title="Send message">'+
                                        '<p style="margin-bottom: 35px;"><img alt="img" style="float:left;margin-right: 10px;" src="<?php echo $themeDir . "/images"; ?>/question.png"/><span>Nhập tên buddy mà bạn muốn gửi IM và ô</span></p>'+
                                        '<p><label for="buddyName">Tên buddy:</label><input style="width:158px" type="text" id="buddyName" /></p>'+
                                    '</div>';
                    
                        j$(htmml).dialog({
                                id: 'dlgSendBuddyMessage',
                                resizable: false, width: 270, height: 170,
                                buttons: {
                                    'Ok': function(){
                                        var buddyName = j$('div.DlgSendBuddyMessageContent').find('input#buddyName').val();
                                        if(buddyName != '')
                                        {
                                            new Request.JSON({
                                                url: "<?php echo $config -> getSetting("site-url")."/chat/chat.php "; ?>", 
                                                secure: false,
                                                onComplete: function(json)
                                                {
                                                    if(json.success == 'true')
                                                    {
                                                        buddyList.setMessageType('Normal');
                                                        buddyList.openDlgChat(buddyName);
                                                    }
                                                    else
                                                        handleError(json);
                                                }
                                            }).post({action: 'getBuddyInfo', userId: '<?php echo $user -> getID() ?>', buddyName: buddyName});
                                            
                                        }
                                        j$(this).dialog('close');
                                    }
                                },
                                close: function(ev, ui)
                                {
                                    ui.remove();
                                },
                                open: function()
                                {
                                    j$('div.DlgSendBuddyMessageContent').find('input#buddyName').focus();
                                }
                        });
                    }
                },
                onDlgChatTextareaEnter: function(id, text)
                {
                    var fn = this;
                    new Request.JSON
                    ({
                        url: "<?php echo $config -> getSetting("site-url")."/chat/chat.php "; ?>", 
                        secure: false,
                        onComplete: function(json)
                        {
                            if(json.success == 'true')
                            {
                                var ms = Base64.decode(json.message);
                                if(buddyList.getMessageType() == 'Warning')
                                    buddyList.warningMessage(id, ms);
                                else if(buddyList.getMessageType() == 'Alert')
                                    buddyList.alertMessage(id, ms);
                                else
                                    buddyList.addDlgChatMessage(id, {sender: fn.options.owner.alias, ms: ms});
                                
                            }
                            else
                                handleError(json);
                        }
                    }).post({action: 'sendMessage', userId: '<?php echo $user -> getID() ?>', message: text, receiver: id, mst: buddyList.getMessageType()});
                }
            });
            
            function newBuddyDlg(buddyList)
            {
                new Request.JSON
                ({
                    url: "<?php echo $config -> getSetting("site-url")."/chat/chat.php "; ?>", 
                    secure: false,
                    onComplete: function(json)
                    {
                        if(json.success == 'true')
                        {
                            var gr = '';
                            j$.each(json.items.groups, function(ii, it)
                            {
                                if(it.id != '')
                                    gr += '<option value="'+it.id.substring(6)+'">'+it.name+'</option>';
                            });
                            
                            var htmml = '<div class="DlgAddBuddyContent flora Toolbox" title="Thêm bạn">'+
                                            '<p style="margin-bottom: 10px;"><img alt="img" style="float:left;margin-right: 10px;" src="<?php echo $themeDir . "/images"; ?>/cool.png"/><span>Nhập tên và chọn nhóm bạn muốn thêm vào danh sách</span></p>'+
                                            '<p><label for="friendName">Tên bạn:</label><input style="width:158px" type="text" id="friendName" /></p>'+
                                            '<p><label>Nhóm:</label><select style="width:162px" >'+gr+'</select></p>'+
                                        '</div>';
                                
                            j$(htmml).dialog({
                                id: 'dlgAddBuddy',
                                resizable: false, width: 270, height: 170,
                                buttons: {
                                    'Thêm bạn': function()
                                    {
                                        var buddyName = j$('div.DlgAddBuddyContent').find('input#friendName').val();
                                        var buddyGroup = j$('div.DlgAddBuddyContent').find('option:selected').val();
                                        if(buddyName != '')
                                        {
                                            new Request.JSON
                                            ({
                                                url: url, 
                                                secure: false,
                                                onComplete: function(json)
                                                {
                                                    if(json.success == 'true')
                                                        buddyList.buildBuddyList(json.items);
                                                    else
                                                        handleError(json);
                                                }
                                            }).post({action: 'addBuddy', userId: '<?php echo $user -> getID() ?>', buddyName: buddyName, groupId: buddyGroup});
                                        }
                                        j$(this).dialog('close');
                                    }
                                },
                                close: function(ev, ui)
                                {
                                    ui.remove();
                                },
                                open: function()
                                {
                                    j$('div.DlgAddBuddyContent').find('input#friendName').focus();
                                }
                            });
                        }
                        else
                            handleError(json);
                    }
                }).post({action: 'getBuddyGroup', userId: '<?php echo $user -> getID() ?>'});
            }
    });
</script>

<?php
    
    include($themeDir . "/footer.php");
    exit();
}

?>
    <!-- used to centre the front page -->  
<div class="Content">
    <form id="container" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
        <div class="RightSide">  
            <div id="login">  
                <div id="loginBox">
                    <?php
                        if(RedirectMessage::hasMessage())
                        {
                            InfoArea::showInfo(RedirectMessage::getMessage(), RedirectMessage::getMessage('title'), RedirectMessage::getMessage('type'));
                            RedirectMessage::removeMessage();
                        }
                    ?>
                    <div id="loginContent"> 
                        <div id="loginContentWrapper"> 
                            <div><!-- this is a hacky fix for IE --> </div>  
                            <h3 class="LoginBoxHeader">Login to Now!chat</h3> 
                            <div class="LoginForm"> 
                                <table>
                                <tbody>
                                    <tr> 
                                        <td class="Label"><label for="userLoginName">username</label> </td>
                                        <td><input type="text" name="userLoginName" tabindex="1" id="userLoginName" size="25" maxlength="25" title="Nhập User Id"></input> </td>
                                    </tr> 
                                    
                                    <tr> 
                                        <td class="Label"><label for="userLoginPass">password</label> </td>
                                        <td><input type="password" name="userLoginPass" tabindex="2" id="userLoginPass" size="16" maxlength="16" title="Nhập User Password"></input> </td>
                                    </tr>  
                                </tbody>
                                </table> 
                                
                                <div class="Buttons" id="submit"> 
                                    <input type="submit" name="login" tabindex="3" id="signin" value="Sign in"></input>
                                </div> 
                            </div> 
                        </div> 
                    </div>   
                    
                    <div id="signupContent">  
                        <h4>Chưa có tài khoản Now!chat?</h4>
                        <small>Đăng ký rất đơn giản</small>
                        
                        <div id="signupNow">
                            <a href="./register.php">Đăng ký ngay!</a>
                        </div>
                        <div style="height: 3px; line-height: 0pt; clear: both;"><!-- fudge --> </div>  
                    </div>  
                </div>  
            </div>   
        </div>  
    </form>
</div> 

<?php include($themeDir . "/footer.php"); ?>